package com.reebake.ideal.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reebake.ideal.json.util.JsonUtil;
import com.reebake.ideal.storage.entity.FilePartDetail;
import com.reebake.ideal.storage.service.FilePartDetailService;
import com.reebake.ideal.storage.service.FilePartRecorderService;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.dromara.x.file.storage.core.upload.FilePartInfo;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class FilePartRecorderServiceImpl implements FilePartRecorderService {
    private final FilePartDetailService filePartDetailService;
    /**
     * 保存文件分片信息
     * @param info 文件分片信息
     */
    @SneakyThrows
    public void saveFilePart(FilePartInfo info) {
        FilePartDetail detail = toFilePartDetail(info);
        if (filePartDetailService.save(detail)) {
            info.setId(detail.getFilePartDetailId());
        }
    }

    /**
     * 删除文件分片信息
     */
    public void deleteFilePartByUploadId(String uploadId) {
        filePartDetailService.remove(new LambdaQueryWrapper<FilePartDetail>().eq(FilePartDetail::getUploadId, uploadId));
    }

    /**
     * 将 FilePartInfo 转成 FilePartDetail
     * @param info 文件分片信息
     */
    public FilePartDetail toFilePartDetail(FilePartInfo info) throws JsonProcessingException {
        FilePartDetail detail = new FilePartDetail();
        detail.setPlatform(info.getPlatform());
        detail.setUploadId(info.getUploadId());
        detail.setETag(info.getETag());
        detail.setPartNumber(info.getPartNumber());
        detail.setPartSize(info.getPartSize());
        detail.setHashInfo(JsonUtil.toJsonStr(info.getHashInfo()));
        detail.setCreateTime(info.getCreateTime());
        return detail;
    }

}
